import type { RadioChangeEvent } from 'antd';
import { Button, Checkbox, InputNumber, message, Radio, Table } from 'antd';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import type { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';
import { getResumeSet, setResume, SetResumeOptions } from './data';

const SetResume: React.FC<any> = () => {
  const [isSet, setIsSet] = useState<boolean>(false);
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  const [saveLoading, setLoading] = useState<boolean>(false);
  const [listData, setListData] = useState<any[]>([]);

  const columns: ColumnsType<any> = [
    {
      title: '司机等级',
      dataIndex: 'gradeName',
      key: 'gradeName',
      width: '120px',
      ellipsis: true,
    },
    {
      title: '当前安全指数与最大安全指数的比值（N）',
      dataIndex: 'address',
      key: 'address',
      width: '130px',
      render(value, record, index) {
        return (
          <div className="flexr alc">
            <span style={{ width: '36px' }}>{record.startRatio}%</span>
            {index == 0 ? (
              <span style={{ margin: '0 10px', minWidth: '36px' }}>≤N≤</span>
            ) : (
              <span style={{ margin: '0 10px', minWidth: '36px' }}>＜N≤</span>
            )}
            <span>{record.endRatio}%</span>
          </div>
        );
      },
    },
    {
      title: '简历是否收费',
      dataIndex: 'charge',
      key: 'charge',
      width: 110,
      render(value, record, index) {
        return isSet ? (
          <Radio.Group
            disabled={isSet ? false : true}
            defaultValue={value || 0}
            onChange={(e: RadioChangeEvent) => {
              const list = listData;
              list[index].charge = e.target.value;
              // list[index].price = '';
              // list[index].opennessLevelArr = [];
              // list[index].opennessLevel = '';
              setListData(list.slice());
            }}
          >
            <Radio value={1}>收费</Radio>
            <Radio value={0}>免费</Radio>
          </Radio.Group>
        ) : (
          <div>{value == 1 ? '收费' : '免费'}</div>
        );
      },
    },
    {
      title: '简历价格(元/份)',
      dataIndex: 'price',
      key: 'price',
      width: 100,
      render(value, record, index) {
        return isSet ? (
          record.charge == 1 ? (
            <InputNumber
              style={{ width: 110 }}
              placeholder="请输入"
              maxLength={10}
              min={0.01}
              max={9999}
              precision={2}
              defaultValue={record.price}
              value={record.price}
              onChange={(e) => {
                setListData((v) => {
                  v[index].price = Number(e);
                  return [...v];
                });
              }}
            ></InputNumber>
          ) : (
            <></>
          )
        ) : (
          <span>{record.charge == 1 ? value : '--'}</span>
        );
      },
    },
    {
      title: '查看简历隐私字段开放程度',
      dataIndex: 'opennessLevelArr',
      key: 'opennessLevelArr',
      width: 200,
      render(value, record, index) {
        return record.charge == 1 ? (
          <Checkbox.Group
            disabled={isSet ? false : true}
            options={SetResumeOptions}
            defaultValue={value}
            value={value}
            onChange={(opennessLevel: CheckboxValueType[]) => {
              const list = listData;
              list[index].opennessLevel = opennessLevel.join(',');
              list[index].opennessLevelArr = opennessLevel;
              setListData(list.slice());
            }}
          />
        ) : (
          <span></span>
        );
      },
    },
  ];
  /**
   * 获取
   */
  const updataList = async () => {
    setTableLoading(true);
    const { data } = await getResumeSet();
    // debugger;
    data.map((v) => {
      v.charge = v.charge || 0;
      v.opennessLevelArr = v.opennessLevel?.split(',').map(Number) || [];
    });
    setTableLoading(false);
    setListData(data.slice());
  };

  useEffect(() => {
    updataList();
  }, [isSet]);

  //校验
  const verification = () => {
    let flag = true;
    if (listData.length) {
      flag = listData.every((item) => {
        if (!(item.charge === 0 || item.charge === 1)) {
          message.error('请完善简历是否收费');
          return false;
        }
        if (item.charge === 1 && !item.price) {
          message.error('请完善收费简历价格');
          return false;
        }
        return true;
      });
      if (!flag) {
        return;
      }
    }
    return flag;
  };

  /*
   * 保存
   */
  const save = async () => {
    if (!verification()) {
      return;
    }
    const postList = listData.slice();
    postList.map((v) => {
      delete v.opennessLevelArr;
      delete v.driverNum;
      v.startRatio = Number(v.startRatio);
      v.endRatio = Number(v.endRatio);
      if (v.charge != 1) {
        v.price = '';
        v.opennessLevel = '';
      }
    });
    setLoading(true);
    setResume(postList).then((res) => {
      setLoading(false);
      if (res.code == '200') {
        message.open({
          type: 'success',
          content: '保存成功',
        });
        updataList();

        setIsSet(false);
      }
    });
  };
  return (
    <div className="safe_boss_page">
      <div style={{ height: '100%', width: '100%', background: '#fff', padding: '16px' }}>
        <div style={{ marginBottom: '32px' }}>
          {!isSet ? (
            <Button
              type="primary"
              onClick={() => {
                setIsSet(true);
              }}
            >
              设置
            </Button>
          ) : (
            <div className="flexr alc">
              <Button
                style={{ marginRight: '10px' }}
                onClick={() => {
                  setIsSet(false);
                }}
              >
                取消
              </Button>

              <Button
                type="primary"
                loading={saveLoading}
                onClick={() => {
                  save();
                }}
              >
                保存
              </Button>
            </div>
          )}
        </div>
        <Table
          sticky
          loading={tableLoading}
          dataSource={listData}
          columns={columns}
          pagination={false}
          scroll={{ x: '100%', y: 'calc(100vh - 205px)' }}
          rowKey="securityIndexLevelId"
        />
      </div>
    </div>
  );
};

export default SetResume;
